package org.example.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.example.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 创建一个用户实现UserDetails接口，作为查询用户权限的返回值
 */
@Data
public class UserDetailsImpl implements UserDetails {
    private String password;
    private String username;
    private String status;
    private Set<String> permsSet;
    private Set<String> roleKeySet;
    private User user;

    // 返回权限字符串的集合和角色key的集合
    @Override
    @JsonIgnore //忽略
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> list=new ArrayList<>();
        for (String perms : permsSet) {
            list.add(new SimpleGrantedAuthority(perms));
        }
        for (String role : roleKeySet) {
            list.add(new SimpleGrantedAuthority("ROLE_"+role)); // ROLE_区分是角色权限还是菜单权限
        }
        return list;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return status.equals("0");
    }
}
